package com.web.exiaodao.business.service.impl;

import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.business.repository.MakeMoneyTableRepository;
import com.web.exiaodao.business.service.MakeMoneyTableService;
import com.web.exiaodao.remote.vo.MakeMoneyTableVo;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("MakeMoneyTableService")
@Transactional(readOnly = false)
public class MakeMoneyTableServiceImpl extends BaseService<MakeMoneyTable> implements MakeMoneyTableService {

    private static final Logger LOGGER = Logger.getLogger(MakeMoneyTableServiceImpl.class);

    @Autowired
    private MakeMoneyTableRepository makeMoneyTableRepository;

    /**
     * 查询单条MakeMoneyTable信息
     * //@param tId
     *
     * @return 返回单个MakeMoneyTable对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<MakeMoneyTable> findOne(Long modelId) throws BusinessException {
        MakeMoneyTable obj = new MakeMoneyTable();
        if (modelId != 0) {
            obj = makeMoneyTableRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<MakeMoneyTable> xr = new XaResult<MakeMoneyTable>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(obj);
            LOGGER.info("后台----->查询单个实体----->MakeMoneyTable");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 分页查询状态非status的MakeMoneyTable数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象MakeMoneyTable集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<MakeMoneyTable>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<MakeMoneyTable> page = makeMoneyTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), MakeMoneyTable.class), pageable);
        XaResult<Page<MakeMoneyTable>> xr = new XaResult<Page<MakeMoneyTable>>();
        xr.setObject(page);
        LOGGER.info("后台----->分页查询实体集合（状态不等于）----->MakeMoneyTable");
        return xr;
    }

    /**
     * 分页查询状态status的MakeMoneyTable数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象MakeMoneyTable集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<MakeMoneyTable>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<MakeMoneyTable> page = makeMoneyTableRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), MakeMoneyTable.class), pageable);
        XaResult<Page<MakeMoneyTable>> xr = new XaResult<Page<MakeMoneyTable>>();
        xr.setObject(page);
        LOGGER.info("后台----->分页查询实体集合（状态等于）----->MakeMoneyTable");
        return xr;
    }

    /**
     * 保存MakeMoneyTable信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<MakeMoneyTable> saveOrUpdate(MakeMoneyTable model) throws BusinessException {
        MakeMoneyTable obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = makeMoneyTableRepository.findOne(model.getId());
        } else {
            obj = new MakeMoneyTable();
        }
        obj.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : obj.getType());
        obj.setMakeMoney_Cost(XaUtil.isNotEmpty(model.getMakeMoney_Cost()) ? model.getMakeMoney_Cost() : obj.getMakeMoney_Cost());
        obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
        obj.setConsumeOrMakeMoney(XaUtil.isNotEmpty(model.getConsumeOrMakeMoney()) ? model.getConsumeOrMakeMoney() : obj.getConsumeOrMakeMoney());
        obj.setOrderNo(XaUtil.isNotEmpty(model.getOrderNo()) ? model.getOrderNo() : obj.getOrderNo());
        obj = makeMoneyTableRepository.save(obj);
        XaResult<MakeMoneyTable> xr = new XaResult<MakeMoneyTable>();
        xr.setObject(obj);
        LOGGER.info("后台新增或编辑数据成功！");
        return xr;
    }

    /**
     * 修改MakeMoneyTable状态，可一次修改多条   3删除  -1锁定  1正常
     * //@param userId
     *
     * @param modelIds
     * @param status
     * @return 返回MakeMoneyTable对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<MakeMoneyTable> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<MakeMoneyTable> xr = new XaResult<MakeMoneyTable>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                MakeMoneyTable obj = makeMoneyTableRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = makeMoneyTableRepository.save(obj);
                }
            }
        }
        LOGGER.info("批量修改数据状态成功！");
        return xr;
    }

    /**
     * 计算亲币总额
     *
     * @param userId
     * @return
     * @throws BusinessException
     */
    @Override
    public XaResult<Integer> calculateMoney(long userId) throws BusinessException {
        XaResult<Integer> xr = new XaResult<>();
        double money = 0;
        try {
            money = NumberUtils.toInt(makeMoneyTableRepository.calculate(userId) + "", 0);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        xr.setObject((int) money);
        return xr;
    }

    /**
     * 签到-孝亲币管理控制器
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public XaResult<Page<MakeMoneyTableVo>> findMakeMoneyTableList(
            Integer nextPage, Integer pageSize, Map<String, Object> filterParams)
            throws BusinessException {
//		SELECT m.id,m.type,m.make_money_cost,u.`user_name`,m.consume_or_make_money,m.create_time 
//		FROM `tb_xa_makemoneytable` m 
//		LEFT JOIN `tb_xa_user` u ON u.`id` = m.user_id
        StringBuffer sql = new StringBuffer("SELECT m.id,m.type,m.make_money_cost,u.`user_name`,m.consume_or_make_money,m.create_time ");
        sql.append("FROM `tb_xa_makemoneytable` m ");
        sql.append("LEFT JOIN `tb_xa_user` u ON u.`id` = m.user_id ");
        sql.append(" WHERE m.`status`<>").append(XaConstant.Status.delete);
        //统计数据库中数据个数
        StringBuffer sql1 = new StringBuffer("SELECT COUNT(*) ");
        sql1.append("FROM `tb_xa_makemoneytable` m ");
        sql1.append("LEFT JOIN `tb_xa_user` u ON u.`id` = m.user_id ");
        sql1.append(" AND m.`status`<>").append(XaConstant.Status.delete);
        //查询条件
        if (XaUtil.isNotEmpty(filterParams.get("EQ_type"))) {
            sql.append(" AND m.type=' ").append(filterParams.get("EQ_type")).append("' ");
            sql1.append(" AND m.type=' ").append(filterParams.get("EQ_type")).append("' ");
        }
        if (XaUtil.isNotEmpty(filterParams.get("EQ_consumeOrMakeMoney"))) {
            sql.append(" AND m.consume_or_make_money=' ").append(filterParams.get("EQ_consumeOrMakeMoney")).append("' ");
            sql1.append(" AND m.consume_or_make_money=' ").append(filterParams.get("EQ_consumeOrMakeMoney")).append("' ");
        }
        sql.append(" ORDER BY m.`create_time` desc");
        sql1.append(" ORDER BY m.`create_time` desc");
        List<Object[]> objs = this.query(sql.toString(), nextPage * pageSize, pageSize);
        List<MakeMoneyTableVo> vos = new ArrayList<MakeMoneyTableVo>();
        for (Object[] obj : objs) {
            UserVo u = new UserVo();
            MakeMoneyTableVo vo = new MakeMoneyTableVo();
            vo.setId(Long.valueOf(obj[0].toString()));
            vo.setType(XaUtil.isEmpty(obj[1]) ? 0 : Long.valueOf(obj[1].toString()));
            vo.setMakeMoney_Cost(XaUtil.isEmpty(obj[2]) ? 0 : Double.valueOf(obj[2].toString()));
            u.setUserName(XaUtil.isEmpty(obj[3]) ? "" : obj[3].toString());
            vo.setConsumeOrMakeMoney(XaUtil.isEmpty(obj[4]) ? 0 : Integer.valueOf(obj[4].toString()));
            vo.setCreateTime(XaUtil.isEmpty(obj[5]) ? "" : obj[5].toString());
            vo.setUserVo(u);
            vos.add(vo);
        }
        //执行查询语句
        List<Object[]> obj1 = this.query(sql1.toString(), null, null);
        //将得到的查询结果强转成int类型
        int count = Integer.parseInt(obj1.get(0) + "");
        //调用分页
        Page<MakeMoneyTableVo> page = new MyPage<MakeMoneyTableVo>(nextPage.intValue(), pageSize.intValue(), vos, count);
        //创建结果集对象xr
        XaResult<Page<MakeMoneyTableVo>> xr = new XaResult<Page<MakeMoneyTableVo>>();
        //将page放入xr
        xr.setObject(page);
        return xr;
    }
}
